package cn.iocoder.yudao.module.system.service.gugu;

import cn.iocoder.yudao.module.system.controller.admin.gugu.dto.MajorRecommendDTO;
import cn.iocoder.yudao.module.system.controller.admin.gugu.dto.MajorRecommendDataDTO;
import cn.iocoder.yudao.module.system.dal.dataobject.gugu.CeeMajorDO;
import cn.iocoder.yudao.module.system.dal.mysql.gugu.CeeMajorMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 专业推荐处理服务实现类
 */
@Service
@Slf4j
public class MajorRecommendServiceImpl implements MajorRecommendService {

    /**
     * 专业推荐信息收集类
     */
    private static class MajorRecommendInfo {
        private final CeeMajorDO major;
        private final Set<String> careerDirections;
        private final Set<String> recommendSchools;

        public MajorRecommendInfo(CeeMajorDO major) {
            this.major = major;
            this.careerDirections = new HashSet<>();
            this.recommendSchools = new HashSet<>();

            // 初始化现有的就业方向
            if (StringUtils.hasText(major.getCareerDirection())) {
                String[] directions = major.getCareerDirection().split(";");
                for (String direction : directions) {
                    if (StringUtils.hasText(direction.trim())) {
                        this.careerDirections.add(direction.trim());
                    }
                }
            }

            // 初始化现有的推荐学校
            if (major.getRecommendSchools() != null) {
                this.recommendSchools.addAll(major.getRecommendSchools());
            }
        }

        public void addCareerDirection(String careerDirection) {
            if (StringUtils.hasText(careerDirection)) {
                this.careerDirections.add(careerDirection.trim());
            }
        }

        public void addRecommendSchool(String schoolName) {
            if (StringUtils.hasText(schoolName)) {
                this.recommendSchools.add(schoolName.trim());
            }
        }

        public boolean updateMajor() {
            boolean needUpdate = false;

            // 设置为推荐专业
            if (!Boolean.TRUE.equals(major.getIsRecommended())) {
                major.setIsRecommended(true);
                needUpdate = true;
            }

            // 更新就业方向
            String newCareerDirection = String.join(";", careerDirections);
            if (!Objects.equals(newCareerDirection, major.getCareerDirection())) {
                major.setCareerDirection(newCareerDirection);
                needUpdate = true;
            }

            // 更新推荐学校
            List<String> newRecommendSchools = new ArrayList<>(recommendSchools);
            if (!Objects.equals(newRecommendSchools, major.getRecommendSchools())) {
                major.setRecommendSchools(newRecommendSchools);
                needUpdate = true;
            }

            return needUpdate;
        }

        public CeeMajorDO getMajor() {
            return major;
        }

        public Set<String> getCareerDirections() {
            return careerDirections;
        }

        public Set<String> getRecommendSchools() {
            return recommendSchools;
        }
    }

    @Resource
    private CeeMajorMapper ceeMajorMapper;

    @Resource
    private ObjectMapper objectMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String processMajorRecommendData() {
        try {
            // 1. 读取JSON文件
            MajorRecommendDataDTO recommendData = loadRecommendDataFromJson();
            if (recommendData == null || recommendData.getRecords() == null) {
                return "JSON文件读取失败或数据为空";
            }

            List<MajorRecommendDTO> records = recommendData.getRecords();
            log.info("读取到推荐数据记录数: {}", records.size());

            // 2. 重置所有专业的推荐状态
            resetAllRecommendStatus();

            // 3. 统计信息
            int totalRecords = records.size();
            int matchedCount = 0;
            int updatedCount = 0;
            Map<String, Integer> directionStats = new HashMap<>();

            // 4. 收集专业推荐信息（按专业ID分组）
            Map<Long, MajorRecommendInfo> majorRecommendMap = new HashMap<>();

            // 5. 处理每条推荐记录
            for (MajorRecommendDTO record : records) {
                String majorName = cleanMajorName(record.getMajorName());
                String schoolName = record.getSchoolName();
                String careerDirection = record.getMajorDir();

                if (!StringUtils.hasText(majorName)) {
                    continue;
                }

                // 统计就业方向
                directionStats.put(careerDirection, directionStats.getOrDefault(careerDirection, 0) + 1);

                // 查找匹配的专业
                List<CeeMajorDO> matchedMajors = findMatchingMajors(majorName);
                if (!matchedMajors.isEmpty()) {
                    matchedCount++;

                    for (CeeMajorDO major : matchedMajors) {
                        // 收集推荐信息而不是立即更新
                        MajorRecommendInfo recommendInfo = majorRecommendMap.computeIfAbsent(major.getId(),
                            k -> new MajorRecommendInfo(major));

                        // 添加就业方向
                        if (StringUtils.hasText(careerDirection)) {
                            recommendInfo.addCareerDirection(careerDirection);
                        }

                        // 添加推荐学校
                        if (StringUtils.hasText(schoolName)) {
                            recommendInfo.addRecommendSchool(schoolName);
                        }
                    }
                }
            }

            // 6. 批量更新专业信息
            for (MajorRecommendInfo recommendInfo : majorRecommendMap.values()) {
                if (recommendInfo.updateMajor()) {
                    ceeMajorMapper.updateById(recommendInfo.getMajor());
                    updatedCount++;
                    log.debug("更新专业推荐信息: {} -> 学校: {}, 方向: {}",
                        recommendInfo.getMajor().getMajorName(),
                        recommendInfo.getRecommendSchools(),
                        recommendInfo.getCareerDirections());
                }
            }

            // 5. 构建结果统计
            StringBuilder result = new StringBuilder();
            result.append("专业推荐数据处理完成！\n");
            result.append("总记录数: ").append(totalRecords).append("\n");
            result.append("匹配到的专业数: ").append(matchedCount).append("\n");
            result.append("更新的专业数: ").append(updatedCount).append("\n");
            result.append("就业方向统计:\n");
            directionStats.forEach((direction, count) ->
                result.append("  ").append(direction).append(": ").append(count).append("个专业\n"));

            log.info("专业推荐数据处理完成: {}", result.toString());
            return result.toString();

        } catch (Exception e) {
            log.error("处理专业推荐数据时发生错误", e);
            return "处理失败: " + e.getMessage();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resetAllRecommendStatus() {
        // 重置所有专业的推荐状态
        List<CeeMajorDO> allMajors = ceeMajorMapper.selectList();
        for (CeeMajorDO major : allMajors) {
            if (Boolean.TRUE.equals(major.getIsRecommended()) || StringUtils.hasText(major.getCareerDirection())) {
                major.setIsRecommended(false);
                major.setCareerDirection(null);
                ceeMajorMapper.updateById(major);
            }
        }
        log.info("已重置所有专业的推荐状态");
    }

    /**
     * 从JSON文件加载推荐数据
     */
    private MajorRecommendDataDTO loadRecommendDataFromJson() {
        try {
            // 从data目录读取JSON文件
            String filePath = "D:/myprojects/ruoyi-vue-pro/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/gugu/data/system_major_recommend.json";
            java.io.File file = new java.io.File(filePath);

            if (!file.exists()) {
                log.error("JSON文件不存在: {}", filePath);
                return null;
            }

            return objectMapper.readValue(file, MajorRecommendDataDTO.class);
        } catch (IOException e) {
            log.error("读取推荐数据JSON文件失败", e);
            return null;
        }
    }

    /**
     * 清理专业名称，去除特殊字符
     */
    private String cleanMajorName(String majorName) {
        if (!StringUtils.hasText(majorName)) {
            return "";
        }

        // 去除不可见字符和特殊标记
        String cleaned = majorName.replaceAll("[\\u200B-\\u200F\\u202A-\\u202E\\u2060-\\u206F]", "")
                                  .replaceAll("‌", "")
                                  .trim();

        // 去除括号及括号内容（如果需要的话）
        // cleaned = cleaned.replaceAll("\\([^\\)]*\\)", "").trim();

        return cleaned;
    }

    /**
     * 查找匹配的专业
     */
    private List<CeeMajorDO> findMatchingMajors(String majorName) {
        // 首先尝试精确匹配
        List<CeeMajorDO> exactMatches = ceeMajorMapper.selectByMajorName(majorName);
        if (!exactMatches.isEmpty()) {
            return exactMatches;
        }

        // 如果没有精确匹配，尝试模糊匹配
        List<CeeMajorDO> allMajors = ceeMajorMapper.selectList();
        return allMajors.stream()
                .filter(major -> {
                    String dbMajorName = cleanMajorName(major.getMajorName());
                    return dbMajorName.contains(majorName) || majorName.contains(dbMajorName);
                })
                .collect(Collectors.toList());
    }


}
